package com.yqkj.zysoft.upms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.easy.common.db.mybatisplus.core.util.PageConvertTool;
import  com.project.easy.common.util.collection.CollectionUtil;
import  com.project.easy.common.util.constants.CommonConstant;
import  com.project.easy.common.util.dto.PageResDto;
import  com.project.easy.common.util.exception.business.BusinessException;
import  com.project.easy.common.util.string.StringUtil;
import com.yqkj.zysoft.upms.entity.FrameworkRole;
import com.yqkj.zysoft.upms.entity.FrameworkRoleAuth;
import com.yqkj.zysoft.upms.entity.dto.FrameWorkRoleAddRequest;
import com.yqkj.zysoft.upms.entity.dto.FrameWorkRoleUpdateRequest;
import com.yqkj.zysoft.upms.entity.dto.PageRoleRequest;
import com.yqkj.zysoft.upms.mapper.FrameworkRoleMapper;
import com.yqkj.zysoft.upms.service.IFrameworkRoleAuthService;
import com.yqkj.zysoft.upms.service.IFrameworkRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author GreatorMan.cool
 * @since 2022-08-10
 */
@Service
public class FrameworkRoleServiceImpl extends ServiceImpl<FrameworkRoleMapper, FrameworkRole> implements IFrameworkRoleService {

    @Autowired
    private IFrameworkRoleAuthService frameworkRoleAuthService;

    /**
     * 获取权限集合
     *
     * @param roleId ID
     * @return 返回功能集合
     */
    @Override
    public String getRoleConfigAuth(Long roleId) {
        if (Objects.isNull(roleId)) {
            throw  new BusinessException("角色ID不能为空!");
        }
        QueryWrapper<FrameworkRoleAuth> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        List<FrameworkRoleAuth> frameworkRoleAuths = frameworkRoleAuthService.list(queryWrapper);
        return  CollectionUtil.convertToStringStr(CollectionUtil.convertToList(frameworkRoleAuths, FrameworkRoleAuth::getAuthInnerCode));
    }
    /**
     * 更新权限功能
     *
     * @param authCodes 权限ID
     * @param roleId    角色ID
     * @return true 成功
     */
    @Override
    @Transactional
    public Boolean updateRoleConfigAuth(String authCodes, Long roleId) {
        if (Objects.isNull(roleId)) {
            throw  new BusinessException("角色编码不能为空!");
        }
        QueryWrapper<FrameworkRoleAuth> deleteWrapper = new QueryWrapper<>();
        deleteWrapper.eq("role_id", roleId);
        frameworkRoleAuthService.remove(deleteWrapper);
        if (StringUtil.isNotBlank(authCodes)) {
            String[] split = authCodes.split(",");
            List<FrameworkRoleAuth> frameworkAuthFunctions = new ArrayList<>(CollectionUtil.listSize(split));
            Set<String> authCodesMap = new HashSet<>(CollectionUtil.listSize(split));

            for (String auth : split) {
                if (StringUtil.isBlank(auth)) {
                    continue;
                }
                if (authCodesMap.contains(auth)) {
                    continue;
                }
                authCodesMap.add(auth);
                FrameworkRoleAuth authFunction = new FrameworkRoleAuth();
                authFunction.setAuthInnerCode(auth);
                authFunction.setRoleId(roleId);
                frameworkAuthFunctions.add(authFunction);
            }
            if (CollectionUtil.isNotNull(frameworkAuthFunctions)) {
                this.frameworkRoleAuthService.saveBatch(frameworkAuthFunctions);
            }
        }
        return Boolean.TRUE;
    }

    /**
     * 新增
     *
     * @param frameWorkRoleAddRequest 参数
     * @return 返回 true 成功 false 失败
     */
    @Override
    public Long add(FrameWorkRoleAddRequest frameWorkRoleAddRequest) {
        Boolean aBoolean = this.verifyCode(frameWorkRoleAddRequest.getRoleCode(), "", null);
        if (aBoolean) {
            throw  new BusinessException("角色编码不能重复");
        }
        FrameworkRole frameworkRole = new FrameworkRole();
        frameworkRole.setRoleCode(frameWorkRoleAddRequest.getRoleCode());
        frameworkRole.setRoleName(frameWorkRoleAddRequest.getRoleName());
        boolean save = this.save(frameworkRole);
        if (save) {
            return frameworkRole.getId();
        }
        throw  new BusinessException("存储失败");
    }

    /**
     * 更新数据
     *
     * @param frameWorkRoleUpdateRequest 参数
     * @return true 成功 false 失败
     */
    @Override
    public Boolean updateObject(FrameWorkRoleUpdateRequest frameWorkRoleUpdateRequest) {
        FrameworkRole frameworkRole = this.getById(frameWorkRoleUpdateRequest.getId());
        if (Objects.isNull(frameworkRole)) {
            throw  new BusinessException("ID非法");
        }
        Boolean aBoolean = verifyCode(frameWorkRoleUpdateRequest.getRoleCode(), "", frameWorkRoleUpdateRequest.getId());
        if (aBoolean) {
            throw  new BusinessException("修改角色编码不能重复");
        }
        frameworkRole.setRoleCode(frameWorkRoleUpdateRequest.getRoleCode());
        frameworkRole.setRoleName(frameWorkRoleUpdateRequest.getRoleName());
        return  this.updateById(frameworkRole);
    }

    /**
     * 分页
     *
     * @param pageRoleRequest 分页查询条件
     * @return 返回数据
     */
    @Override
    public PageResDto<FrameworkRole> pageList(PageRoleRequest pageRoleRequest) {
        Page<FrameworkRole> page = new Page<>(pageRoleRequest.getPageNum(), pageRoleRequest.getPageSize());
        QueryWrapper<FrameworkRole> queryWrapper = new QueryWrapper<>();
        if (StringUtil.isNotBlank(pageRoleRequest.getCode())) {
            queryWrapper.like("role_code", pageRoleRequest.getCode());
        }
        if (StringUtil.isNotBlank(pageRoleRequest.getName())) {
            queryWrapper.eq("role_name", pageRoleRequest.getName());
        }
        queryWrapper.eq("has_del", Boolean.FALSE);

        Page<FrameworkRole> result  = this.baseMapper.selectPage(page, queryWrapper);
        return PageConvertTool.convert(result);
    }

    /**
     * 验证数据
     *
     * @param workRoleUpdateRequest 参数
     * @return true 验证成功 false 验证失败
     */
    @Override
    public Boolean verifyCode(FrameWorkRoleUpdateRequest workRoleUpdateRequest) {
        return  this.verifyCode(workRoleUpdateRequest.getRoleCode(), "", workRoleUpdateRequest.getId());
    }
    /**
     * 验证数据
     * @param  sysCode 系统编码
     * @param code 编码
     * @param id ID
     * @return true 验证成功 false 验证失败
     */
    private Boolean verifyCode(String code, String sysCode, Long id) {
        if (StringUtil.isBlank(code)) {
            return Boolean.FALSE;
        }
        FrameworkRole dto  = this.querByCodeAndSysCode(code, sysCode);
        if (Objects.nonNull(id) && Objects.nonNull(dto)) {
            if (dto.getId().compareTo(id) == 0) {
                return Boolean.FALSE;
            }
        }
        return Objects.nonNull(dto);
    }
    /**
     * 根据编码与系统查询
     * @param code 编码
     * @param sysCode 系统编码
     * @return true 成功 false 失败
     */
    private FrameworkRole querByCodeAndSysCode(String code, String sysCode) {
        if (StringUtil.isBlank(sysCode)) {
            sysCode = CommonConstant.DEFAULT_SYS_CODE;
        }
        QueryWrapper<FrameworkRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_code", code);
        queryWrapper.eq("has_del", Boolean.FALSE);
        return this.getOne(queryWrapper);
    }
    /**
     * 启用
     *
     * @param id ID
     * @return true 启用成功 false 启用失败
     */
    @Override
    public Boolean able(Long id) {
        if (Objects.isNull(id)) {
            throw new BusinessException("参数不能为空");
        }
        FrameworkRole frameworkRole = this.baseMapper.selectById(id);
        if (Objects.isNull(frameworkRole)) {
            throw  new BusinessException("参数非法!");
        }
        if (frameworkRole.getStatus()) {
            throw  new BusinessException("启用不能再次启用!");
        }
        frameworkRole.setStatus(Boolean.TRUE);
        this.baseMapper.updateById(frameworkRole);
        return Boolean.TRUE;
    }

    /**
     * 启用
     *
     * @param id ID
     * @return true 启用成功 false 启用失败
     */
    @Override
    public Boolean disAble(Long id) {
        if (Objects.isNull(id)) {
            throw new BusinessException("参数不能为空");
        }
        FrameworkRole frameworkRole = this.baseMapper.selectById(id);
        if (Objects.isNull(frameworkRole)) {
            throw  new BusinessException("参数非法!");
        }
        if (!frameworkRole.getStatus()) {
            throw  new BusinessException("禁用不能再次禁用!");
        }
        frameworkRole.setStatus(Boolean.FALSE);
        this.baseMapper.updateById(frameworkRole);
        return Boolean.TRUE;
    }
}
